package com.tchcn.supermarket.ui.fragment;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fanwe.library.adapter.http.model.SDResponse;
import com.tchcn.library.dao.StoreBeanDao;
import com.tchcn.library.http.AppRequestCallback;
import com.tchcn.library.model.BaseActModel;
import com.tchcn.library.model.StoreBean;
import com.tchcn.library.model.UserInfoModel;
import com.tchcn.library.utils.LogUtil;
import com.tchcn.supermarket.R;
import com.tchcn.supermarket.adapter.UserManageAdapter;
import com.tchcn.supermarket.base.BaseRecyclerAdapter;
import com.tchcn.supermarket.base.SBaseFragment;
import com.tchcn.supermarket.common.SCommonInterface;
import com.tchcn.supermarket.model.PageModel;
import com.tchcn.supermarket.model.PtActModel;
import com.tchcn.supermarket.model.RoleActModel;
import com.tchcn.supermarket.model.UserActModel;
import com.tchcn.supermarket.utils.AnimationUtil;
import com.tchcn.supermarket.utils.GlideUtil;
import com.tchcn.supermarket.utils.SDToast;
import com.tchcn.supermarket.utils.ViewBinder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *  后台管理-用户管理
 * Created by humu on 2018/10/30.
 */

public class UserManageFragment extends SBaseFragment {

    private RecyclerView rv_user;
    private RecyclerView rv_permission;
    private TextView tv_return;
    private TextView tv_operate_title;
    private Button btn_left;
    private Button btn_right;
    private TextView tv_filter_location;
    private EditText et_user_name;
    private EditText et_pwd;
    private RelativeLayout rl_popup_items;
    private RecyclerView rv_popup;
    private TextView tv_chose_location;

    private static UserManageFragment fragment;
    private int checkedUserIndex = -1;
    private UserManageAdapter userAdapter;
    private String checkedUserId = "";
    private PopupItemAdapter popupItemAdapter;
    private View view_mask;
    private StoreBeanAdapter storeBeanAdapter;
    private TextView tv_chose_role;
    private TextView tv_filter_num;
    private SimpleDraweeView sdv;

    private List<String> stateList = new ArrayList<>();
    private TextView tv_chose_state;
    private UserStateAdapter userStateAdapter;
    private TextView tv_chose_pt;
    private UserPtAdapter userPtAdapter;

    private String currentPtId = ""; //权限组id
    private String currentRoleName = ""; //当前身份
    private String currentState = ""; //当前状态 0正常 1停用
    private String currentLocationId = ""; //当前门店id
    private String currentPtName = "";
    private UserStoreBeanAdapter userStoreBeanAdapter;
    private List<UserActModel.UserData.UserModel> userModelList;

    public static UserManageFragment getInstance(){
        if(fragment == null){
            fragment = new UserManageFragment();
        }
        return fragment;
    }

    @Override
    protected int onCreateContentView() {
        return R.layout.sfragment_user_manage;
    }

    @Override
    protected void initView() {
        initUI();
        initUsers();
    }

    private void initUsers() {
        SCommonInterface.getUsers(activity.getSupplierId(), new AppRequestCallback<UserActModel>() {
            @Override
            protected void onSuccess(SDResponse sdResponse) {
                LogUtil.e("getUsers",sdResponse.getResult());
                if(actModel.isOk()){
                    UserActModel.UserData data = actModel.getData();
                    if(data != null){
                        userModelList = data.getRes();
                        if(userModelList != null && userModelList.size() > 0){
                            if("全部用户管理列表".equals(tv_filter_location.getText().toString())){
                                userAdapter.setDatas(userModelList);
                                ViewBinder.setTextView(tv_filter_num,"("+userModelList.size()+")");
                            }else{
                                for(UserActModel.UserData.UserModel model : userModelList){
                                    if(!model.getLocation_name().equals(tv_filter_location.getText().toString())){
                                        userModelList.remove(model);
                                    }
                                }
                                userAdapter.setDatas(userModelList);
                                ViewBinder.setTextView(tv_filter_num,"("+userModelList.size()+")");
                            }
                        }else{
                            userModelList = new ArrayList<>();
                            userAdapter.setDatas(userModelList);
                            ViewBinder.setTextView(tv_filter_num,"("+0+")");
                        }
                    }else{
                        userModelList = new ArrayList<>();
                        userAdapter.setDatas(userModelList);
                        ViewBinder.setTextView(tv_filter_num,"("+0+")");
                    }
                }else{
                    userModelList = new ArrayList<>();
                    userAdapter.setDatas(userModelList);
                    ViewBinder.setTextView(tv_filter_num,"("+0+")");
                }
            }
        });
    }

    private void initUI() {
        sdv = find(R.id.sdv);
        RelativeLayout rl_change_location = find(R.id.rl_change_location);
        rl_change_location.setOnClickListener(this);
        rv_user = find(R.id.rv_user);
        rv_permission = find(R.id.rv_permission);
        rv_user.setLayoutManager(new GridLayoutManager(context,2));
        rv_permission.setLayoutManager(new GridLayoutManager(context,4));
        rv_permission.setNestedScrollingEnabled(false);
        userAdapter = new UserManageAdapter();
        userAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<UserActModel.UserData.UserModel>() {
            @Override
            public void onItemClick(View covertView, int position, UserActModel.UserData.UserModel data) {
                if(checkedUserIndex >= 0){
                    userAdapter.getItem(checkedUserIndex).setChecked(false);
                }
                data.setChecked(true);
                userAdapter.notifyDataSetChanged();
                checkedUserIndex = position;
                checkedUserId = data.getId();
                initUserInfo(data);
            }
        });
        rv_user.setAdapter(userAdapter);

        tv_filter_num = find(R.id.tv_filter_num);
        tv_return = find(R.id.tv_return);
        tv_return.setOnClickListener(this);
        tv_operate_title = find(R.id.tv_operate_title);
        btn_left = find(R.id.btn_left);
        btn_right = find(R.id.btn_right);
        btn_left.setOnClickListener(this);
        btn_right.setOnClickListener(this);
        tv_filter_location = find(R.id.tv_filter_location);
        et_user_name = find(R.id.et_user_name);
        et_pwd = find(R.id.et_pwd);
        rl_popup_items = find(R.id.rl_popup_items);
        rv_popup = find(R.id.rv_popup);
        rv_popup.setLayoutManager(new LinearLayoutManager(context));
        popupItemAdapter = new PopupItemAdapter();
        popupItemAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<String>() {
            @Override
            public void onItemClick(View covertView, int position, String data) {
                ViewBinder.setTextView(tv_chose_role,data);
                currentRoleName = data;
                hideItemsPopup();
            }
        });

        storeBeanAdapter = new StoreBeanAdapter();
        storeBeanAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<StoreBean>() {
            @Override
            public void onItemClick(View covertView, int position, StoreBean data) {
                ViewBinder.setTextView(tv_chose_location,data.getLocation_name());
                currentLocationId = data.getId()+"";
                hideItemsPopup();
            }
        });
        userStoreBeanAdapter = new UserStoreBeanAdapter();
        userStoreBeanAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<StoreBean>() {
            @Override
            public void onItemClick(View covertView, int position, StoreBean data) {
                ViewBinder.setTextView(tv_filter_location,data.getLocation_name());
                if(checkedUserIndex >= 0){
                    userAdapter.getItem(checkedUserIndex).setChecked(false);
                }
                checkedUserId = "";
                checkedUserIndex = -1;
                hideItemsPopup();
                initUsers();
                reset();
            }
        });
        userStateAdapter = new UserStateAdapter();
        userStateAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<String>() {
            @Override
            public void onItemClick(View covertView, int position, String data) {
                ViewBinder.setTextView(tv_chose_state,data);
                if("正常".equals(data)){
                    currentState = "0";
                }else if("停用".equals(data)){
                    currentState = "1";
                }
                hideItemsPopup();
            }
        });
        userPtAdapter = new UserPtAdapter();
        userPtAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<PtActModel.PtData.PtModel>() {
            @Override
            public void onItemClick(View covertView, int position, PtActModel.PtData.PtModel data) {
                ViewBinder.setTextView(tv_chose_pt,data.getName());
                currentPtId = data.getId();
                currentPtName = data.getName();
                hideItemsPopup();
            }
        });
        view_mask = find(R.id.view_mask);
        view_mask.setOnClickListener(this);
        tv_chose_location = find(R.id.tv_chose_location);
        LinearLayout ll_chose_location = find(R.id.ll_chose_location);
        ll_chose_location.setOnClickListener(this);
        tv_chose_location.setOnClickListener(this);
        tv_chose_role = find(R.id.tv_chose_role);
        tv_chose_role.setOnClickListener(this);
        tv_chose_state = find(R.id.tv_chose_state);
        tv_chose_state.setOnClickListener(this);
        tv_chose_pt = find(R.id.tv_chose_pt);
        tv_chose_pt.setOnClickListener(this);
        stateList.clear();
        stateList.add("正常");
        stateList.add("停用");
    }

    private void initUserInfo(UserActModel.UserData.UserModel userModel) {
        GlideUtil.load(context,userModel.getUser_image(),sdv);
        ViewBinder.setTextView(tv_operate_title,"编辑用户信息");
        tv_return.setVisibility(View.VISIBLE);
        ViewBinder.setTextView(btn_left,"删除用户信息");
        btn_left.setVisibility(View.VISIBLE);
        btn_left.setTextColor(getResources().getColor(R.color.btn_del_good_info));
        if(userModel != null){
            ViewBinder.setTextView(et_user_name,userModel.getUser_name());
            ViewBinder.setTextView(et_pwd,userModel.getUser_pwd());
            ViewBinder.setTextView(tv_chose_location,userModel.getLocation_name());
            currentLocationId = userModel.getLocation_id();
            ViewBinder.setTextView(tv_chose_role,userModel.getApprole_name());
            ViewBinder.setTextView(tv_chose_pt,userModel.getRole_name());
            currentRoleName = userModel.getApprole_name();
            currentPtId = userModel.getRole_id();
            currentPtName = userModel.getRole_name();
            currentState = userModel.getDisabled();
            if("0".equals(currentState)){
                ViewBinder.setTextView(tv_chose_state,"正常");
            }else if("1".equals(currentState)){
                ViewBinder.setTextView(tv_chose_state,"停用");
            }
        }
    }

    private void clearCurrentUserInfo(){
        ViewBinder.setTextView(et_user_name,"");
        ViewBinder.setTextView(et_pwd,"");
        ViewBinder.setTextView(tv_chose_location,"");
        currentLocationId = "";
        ViewBinder.setTextView(tv_chose_role,"");
        ViewBinder.setTextView(tv_chose_pt,"");
        ViewBinder.setTextView(tv_chose_state,"");
        currentRoleName = "";
        currentPtId = "";
        currentPtName = "";
        currentState = "";
    }

    private void reset(){
        ViewBinder.setTextView(tv_operate_title,"添加用户信息");
        tv_return.setVisibility(View.GONE);
        ViewBinder.setTextView(btn_left,"保存并继续新增");
        btn_left.setVisibility(View.GONE);
        btn_left.setTextColor(getResources().getColor(R.color.main_blue));
        checkedUserIndex = -1;
        checkedUserId = "";
        ArrayList<UserActModel.UserData.UserModel> datas = userAdapter.getDatas();
        if(datas != null && datas.size() > 0){
            for(UserActModel.UserData.UserModel userModel : datas){
                userModel.setChecked(false);
            }
            userAdapter.notifyDataSetChanged();
        }
        clearCurrentUserInfo();
    }

    public void showItemsPopup(){
        if(rl_popup_items.getVisibility() == View.GONE){
            rl_popup_items.startAnimation(AnimationUtil.getMaskViewAppearAnim());
            rl_popup_items.setVisibility(View.VISIBLE);
        }
        showViewMask();
    }

    private void hideItemsPopup(){
        if(rl_popup_items.getVisibility() == View.VISIBLE){
            rl_popup_items.startAnimation(AnimationUtil.getMaskViewDisappearAnim());
            rl_popup_items.setVisibility(View.GONE);
        }
        hideViewMask();
    }

    private void hideViewMask(){
        view_mask.startAnimation(AnimationUtil.getMaskViewDisappearAnim());
        view_mask.setVisibility(View.GONE);
    }

    private void showViewMask(){
        view_mask.startAnimation(AnimationUtil.getMaskViewAppearAnim());
        view_mask.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id == R.id.tv_return){
            reset();
        }else if(id == R.id.btn_left || id == R.id.btn_right){

            final String userName = et_user_name.getText().toString();
            if(TextUtils.isEmpty(userName)){
                SDToast.showToast(context,"请输入用户名");
                return;
            }
            final String userPwd = et_pwd.getText().toString();
            if(TextUtils.isEmpty(userPwd)){
                SDToast.showToast(context,"请输入密码");
                return;
            }
            if(TextUtils.isEmpty(currentLocationId)){
                SDToast.showToast(context,"请选择门店");
                return;
            }
            if(TextUtils.isEmpty(currentRoleName)){
                SDToast.showToast(context,"请选择用户角色");
                return;
            }
            if(TextUtils.isEmpty(currentPtId)){
                SDToast.showToast(context,"请选择用户权限");
                return;
            }
            if(TextUtils.isEmpty(currentState)){
                SDToast.showToast(context,"请选择用户状态");
                return;
            }
            if(id == R.id.btn_left){
                if("添加用户信息".equals(tv_operate_title.getText().toString())){
                    //保存并继续新增
                    SCommonInterface.addNewAccount(UserInfoModel.getUser_id(),
                            userPwd, userName, activity.getSupplierId(), activity.getLocationId(),
                            currentPtId, currentRoleName, currentState, new AppRequestCallback<BaseActModel>() {
                                @Override
                                protected void onSuccess(SDResponse sdResponse) {
                                    reset();
                                }

                                @Override
                                protected void onFinish(SDResponse resp) {
                                    super.onFinish(resp);
                                    initUsers();
                                }
                            });
                }else if("编辑用户信息".equals(tv_operate_title.getText().toString())){
                    //删除用户信息
                    SCommonInterface.delAccount(checkedUserId, new AppRequestCallback<BaseActModel>() {
                        @Override
                        protected void onSuccess(SDResponse sdResponse) {
                            if("1".equals(actModel.getCode())){
                                checkedUserId = "";
                                checkedUserIndex = -1;
                                reset();
                                initUsers();
                            }
                            SDToast.showToast(context,actModel.getMsg());
                        }
                    });
                }
            }else{
                if("添加用户信息".equals(tv_operate_title.getText().toString())){
                    //保存用户信息
                    SCommonInterface.addNewAccount(UserInfoModel.getUser_id(),
                            userPwd, userName, activity.getSupplierId(), activity.getLocationId(),
                            currentPtId, currentRoleName, currentState, new AppRequestCallback<BaseActModel>() {
                                @Override
                                protected void onSuccess(SDResponse sdResponse) {
                                    reset();
                                    SDToast.showToast(context,actModel.getMsg());
                                }

                                @Override
                                protected void onFinish(SDResponse resp) {
                                    super.onFinish(resp);
                                    initUsers();
                                }

                            });
                }else if("编辑用户信息".equals(tv_operate_title.getText().toString())){
                    //编辑
                    SCommonInterface.updateAccount(checkedUserId, UserInfoModel.getUser_id(), currentLocationId,
                            userName, userPwd, currentPtId, currentRoleName, currentState, new AppRequestCallback<BaseActModel>() {
                                @Override
                                protected void onSuccess(SDResponse sdResponse) {
                                    if("1".equals(actModel.getCode())){
                                        UserActModel.UserData.UserModel userModel = userAdapter.getItem(checkedUserIndex);
                                        userModel.setLocation_id(currentLocationId);
                                        userModel.setUser_name(userName);
                                        userModel.setUser_pwd(userPwd);
                                        userModel.setRole_id(currentPtId);
                                        userModel.setRole_name(currentPtName);
                                        userModel.setDisabled(currentState);
                                        userModel.setApprole_name(currentRoleName);
                                        userAdapter.notifyDataSetChanged();
                                    }
                                    SDToast.showToast(context,actModel.getMsg());
                                }
                            });
                }
            }

        }else if(id == R.id.view_mask){
            hideItemsPopup();
        }else if(id == R.id.tv_chose_location || id == R.id.ll_chose_location){
            //选择门店
            rv_popup.setAdapter(storeBeanAdapter);
            List<StoreBean> storeBeanList = StoreBeanDao.queryModel();
            storeBeanAdapter.setDatas(storeBeanList);
            showItemsPopup();
        }else if(id == R.id.tv_chose_role){
            SCommonInterface.getRoles(new AppRequestCallback<RoleActModel>() {
                @Override
                protected void onSuccess(SDResponse sdResponse) {
                    if("200".equals(actModel.getCode())){
                        RoleActModel.RoleData data = actModel.getData();
                        if(data != null){
                            String[] roles = data.getList();
                            rv_popup.setAdapter(popupItemAdapter);
                            popupItemAdapter.setDatas(Arrays.asList(roles));
                            showItemsPopup();
                        }
                    }
                }
            });
        }else if(id == R.id.tv_chose_state){
            rv_popup.setAdapter(userStateAdapter);
            userStateAdapter.setDatas(stateList);
            showItemsPopup();
        }else if(id == R.id.tv_chose_pt){
            SCommonInterface.getCashPts(UserInfoModel.getUser_id(), new AppRequestCallback<PtActModel>() {
                @Override
                protected void onSuccess(SDResponse sdResponse) {
                    if(actModel.isOk()){
                        PtActModel.PtData data = actModel.getData();
                        if(data != null){
                            List<PtActModel.PtData.PtModel> ptModelList = data.getRes();
                            if(ptModelList != null && ptModelList.size() > 0){
                                rv_popup.setAdapter(userPtAdapter);
                                userPtAdapter.setDatas(ptModelList);
                                showItemsPopup();
                            }
                        }
                    }
                }
            });
        }else if(id == R.id.rl_change_location){ //修改门店（筛选用户）
            rv_popup.setAdapter(userStoreBeanAdapter);
            List<StoreBean> storeBeanList = StoreBeanDao.queryModel();
            StoreBean storeBean = new StoreBean();
            storeBean.setLocation_name("全部用户管理列表");
            storeBeanList.add(0,storeBean);
            userStoreBeanAdapter.setDatas(storeBeanList);
            showItemsPopup();
        }
    }

    class PopupItemAdapter extends BaseRecyclerAdapter<String>{

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.sitem_popup_item;
        }

        @Override
        public void setUpData(CommonHolder holder, int position, int viewType, String data) {
            TextView tv_item_name = getView(holder,R.id.tv_item_name);
            ImageView iv_checked = getView(holder,R.id.iv_checked);
            ViewBinder.setTextView(tv_item_name,data);
            if(tv_chose_role.getText().toString().equals(data)){
                tv_item_name.setTextColor(getResources().getColor(R.color.main_blue));
                iv_checked.setVisibility(View.VISIBLE);
            }else{
                tv_item_name.setTextColor(getResources().getColor(R.color.six_six));
                iv_checked.setVisibility(View.GONE);
            }
        }
    }

    class UserStateAdapter extends BaseRecyclerAdapter<String>{

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.sitem_popup_item;
        }

        @Override
        public void setUpData(CommonHolder holder, int position, int viewType, String data) {
            TextView tv_item_name = getView(holder,R.id.tv_item_name);
            ImageView iv_checked = getView(holder,R.id.iv_checked);
            ViewBinder.setTextView(tv_item_name,data);
            if(tv_chose_state.getText().toString().equals(data)){
                tv_item_name.setTextColor(getResources().getColor(R.color.main_blue));
                iv_checked.setVisibility(View.VISIBLE);
            }else{
                tv_item_name.setTextColor(getResources().getColor(R.color.six_six));
                iv_checked.setVisibility(View.GONE);
            }
        }
    }

    //门店选择
    class UserStoreBeanAdapter extends BaseRecyclerAdapter<StoreBean>{

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.sitem_popup_item;
        }

        @Override
        public void setUpData(CommonHolder holder, int position, int viewType, StoreBean data) {
            TextView tv_item_name = getView(holder,R.id.tv_item_name);
            ImageView iv_checked = getView(holder,R.id.iv_checked);
            ViewBinder.setTextView(tv_item_name,data.getLocation_name());
            if(tv_filter_location.getText().toString().equals(data.getLocation_name())){
                tv_item_name.setTextColor(getResources().getColor(R.color.main_blue));
                iv_checked.setVisibility(View.VISIBLE);
            }else{
                tv_item_name.setTextColor(getResources().getColor(R.color.six_six));
                iv_checked.setVisibility(View.GONE);
            }
        }
    }

    //门店选择
    class StoreBeanAdapter extends BaseRecyclerAdapter<StoreBean>{

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.sitem_popup_item;
        }

        @Override
        public void setUpData(CommonHolder holder, int position, int viewType, StoreBean data) {
            TextView tv_item_name = getView(holder,R.id.tv_item_name);
            ImageView iv_checked = getView(holder,R.id.iv_checked);
            ViewBinder.setTextView(tv_item_name,data.getLocation_name());
            if(tv_chose_location.getText().toString().equals(data.getLocation_name())){
                tv_item_name.setTextColor(getResources().getColor(R.color.main_blue));
                iv_checked.setVisibility(View.VISIBLE);
            }else{
                tv_item_name.setTextColor(getResources().getColor(R.color.six_six));
                iv_checked.setVisibility(View.GONE);
            }
        }
    }

    class UserPtAdapter extends BaseRecyclerAdapter<PtActModel.PtData.PtModel>{

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.sitem_popup_item;
        }

        @Override
        public void setUpData(CommonHolder holder, int position, int viewType, PtActModel.PtData.PtModel data) {
            TextView tv_item_name = getView(holder,R.id.tv_item_name);
            ImageView iv_checked = getView(holder,R.id.iv_checked);
            ViewBinder.setTextView(tv_item_name,data.getName());
            if(tv_chose_pt.getText().toString().equals(data.getName())){
                tv_item_name.setTextColor(getResources().getColor(R.color.main_blue));
                iv_checked.setVisibility(View.VISIBLE);
            }else{
                tv_item_name.setTextColor(getResources().getColor(R.color.six_six));
                iv_checked.setVisibility(View.GONE);
            }
        }
    }

}
